PG = require('fckoa/db/pg')
SESSION = require './_session'
bcrypt = require 'bcrypt'

module.exports = require('./_router/user') {
get:{

id:(ctx)->
    ctx.body = ctx.state.user or 0

meta:(ctx)->
    user = ctx.state.user

    if user
        body = {
            id:user
        }

        mail_id = await PG.val('auth.user_mail', user)
        if mail_id
            body.mail = await PG.val('auth.mail', mail_id)

        name = await PG.val('auth.user', user)
        if name
            body.name = name

    else
        body = 0
    ctx.body = body
}
post : {
login:(ctx)->
    await require('./_captcha')(ctx)
    {password, account} = ctx.request.body

    [user_id] = await require('./_account')(account)

    if await bcrypt.compare(
        password
        await PG.val("auth.password", user_id)
    )
        ctx.login user_id
    else
        raise password:1

    ctx.body = 0

logout:(ctx)->
    user = ctx.state.user
    if user
        await SESSION.logout user
    ctx.body = ''
}
}
